//
//  MedicineListController.swift
//  YiYaoHui
//
//  Created by 高永效 on 15/11/30.
//  Copyright © 2015年 EgeTart. All rights reserved.
//

import UIKit
import Alamofire
import MBProgressHUD

//中西药的controller ，请求放数据

class MedicineListController: UIViewController {
    
    @IBOutlet weak var medicineTableView: UITableView!
    var medicineType = ""
    var secondLevelData: SecondLevelData!
    var fourthLevelData: FourthLevelData!
    var enterpriseForthLevelID : String!
    var selectedMedicine: Medicine!
    
    //请求的
    var enterpriseSecondLevelMedicines = [EnterpriseSecondLevelMedicine]()//看见的一级
    var enterpriseFourthLevelMedicines = [EnterpriseForthLevelMedicine]()//展开的二级
    var id = 1 //1:第二个tab显示的本地数据库的药品 ； 2:具体企业请求的药品
    var enterpriseID : String! //具体企业的id，需要显示具体企业的药品
    var secondLevelMedicineID: Int!//每一个二级药物的id，就是子类的“父类”id
    var forthLevelMedicineID: Int!//展开的每行药品的id，作为药品列表的药品“父类”id
    //展开后选中
    var selectedForthMedicine : EnterpriseForthLevelMedicine!
    var enterpriseMedicineType = 5 //中药3 西药4 , 5是初始化随便定的
    var isExpand = [Bool]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if self.id == 2{
            getEnterpriseType(enterpriseMedicineType)
        } else {
            secondLevelData = SecondLevelData(medicineType: medicineType)
            fourthLevelData = FourthLevelData(secondLevelData: secondLevelData, medicineType: medicineType)
            isExpand = [Bool](count: secondLevelData.secondLevelMedicines.count, repeatedValue: false)
        }
        medicineTableView.tableFooterView = UIView(frame: CGRectZero)
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        if self.id == 2 {
            let forthLavelController = self.storyboard?.instantiateViewControllerWithIdentifier("LastLevelController") as! LastLevelMedicineController
            forthLavelController.enterpriseType = self.enterpriseMedicineType
        } else {
         NSNotificationCenter.defaultCenter().postNotificationName("MedicineControllerAppear", object: nil, userInfo: ["medicineType": medicineType])
        }
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "toLastLevel" {
            let destinationVC = segue.destinationViewController as! LastLevelMedicineController
            destinationVC.medicineType = medicineType
            destinationVC.medicineParentID = selectedMedicine.id
        }
    }
}

extension MedicineListController: UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        if self.id == 2 {
             return enterpriseSecondLevelMedicines.count
        } else {
            return secondLevelData.secondLevelMedicines.count
        }
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if indexPath.row  == 0 {
            let cell = tableView.dequeueReusableCellWithIdentifier("secondLevelCell",forIndexPath:  indexPath) as! HeaderCell
            if isExpand[indexPath.section] {
                cell.stateImageView.image = UIImage(named: "close")
            }
            else {
                cell.stateImageView.image = UIImage(named: "expand")
            }
            if self.id == 2 {
                cell.secondLevelLabel.text = enterpriseSecondLevelMedicines[indexPath.section].enterpriseSecondLevelMedicineName
                var str = ""
                for forthMedicine in 0 ... self.enterpriseFourthLevelMedicines.count - 1{
                    str +=  self.enterpriseFourthLevelMedicines[forthMedicine].enterpriseForthLevelMedicineName + "   "
                }
                cell.fourthLevelLabel.text = str
            } else {
                cell.secondLevelLabel.text = secondLevelData.secondLevelMedicines[indexPath.section].name
                let singleTypeMedicines = fourthLevelData.fourthLevelMedicins[indexPath.section]
                var str = ""
                for medicine in singleTypeMedicines {
                    str += medicine.name + " "
                }
                cell.fourthLevelLabel.text = str
            }
            return cell

        } else {
            let cell = tableView.dequeueReusableCellWithIdentifier("fourthLevelCell",forIndexPath: indexPath)
            let fourthLevelLabel = cell.viewWithTag(501) as! UILabel
            if self.id  == 2 {
                fourthLevelLabel.text = enterpriseFourthLevelMedicines[indexPath.row - 1].enterpriseForthLevelMedicineName
                            } else {
                let singleTypeMedicines = fourthLevelData.fourthLevelMedicins[indexPath.section]
                fourthLevelLabel.text = singleTypeMedicines[indexPath.row - 1].name
            }
            return cell
        }
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 50
        }
        return 44
    }
    
    //有多少个section，就执行多少次
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if isExpand[section] == true { //展开了
            if self.id == 2{
                return enterpriseFourthLevelMedicines.count + 1
            } else {
                return fourthLevelData.fourthLevelMedicins[section].count + 1
            }
        }
        return 1
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if self.id == 2 {
        if indexPath.row == 0 {
            isExpand[indexPath.section] = !isExpand[indexPath.section]
            tableView.reloadSections(NSIndexSet(index: indexPath.section), withRowAnimation: UITableViewRowAnimation.Automatic)
        }
        else { //展开了
            let forthMedicines = enterpriseFourthLevelMedicines[indexPath.row - 1]
            selectedForthMedicine = forthMedicines
            
            let forthLavelController = self.storyboard?.instantiateViewControllerWithIdentifier("LastLevelController") as! LastLevelMedicineController
            forthLavelController.forthMedicineID =  enterpriseForthLevelID
            forthLavelController.enterpriseID = self.enterpriseID
            forthLavelController.enterpriseType = self.enterpriseMedicineType
            forthLavelController.id = 2
            self.navigationController?.pushViewController(forthLavelController, animated: true)
            }
                    tableView.deselectRowAtIndexPath(indexPath, animated: true)
        } else {
            if indexPath.row == 0 {
                isExpand[indexPath.section] = !isExpand[indexPath.section]
                tableView.reloadSections(NSIndexSet(index: indexPath.section), withRowAnimation: UITableViewRowAnimation.Automatic)
            }
                else {
                    let singleTypeMedicines = fourthLevelData.fourthLevelMedicins[indexPath.section]
                    selectedMedicine = singleTypeMedicines[indexPath.row - 1]
                    performSegueWithIdentifier("toLastLevel", sender: self)
                        }
        }
    }
}

//请求每一个企业的药品
extension MedicineListController {
//    type参数:中药－3 ；西药－4
//    请求西药
    func getEnterpriseType(type : Int) {
    
        let enterpriseTypeURL = "http://112.74.131.194:8080/MedicineProject/App/user/getEnterTypes"
        
        Alamofire.request(.POST, enterpriseTypeURL, parameters: ["enterpriseId": enterpriseID,"type":type], encoding: ParameterEncoding.URL, headers: nil).responseJSON { (_, _, result) -> Void in
            
            if let value = result.value {
                if let Medicine = value["parentTypes"] as? [Dictionary<String, AnyObject>] {
                    for item in Medicine {
                        let enterpriseSecondLevelMedicine = EnterpriseSecondLevelMedicine(enterpriseSecondLevelMedicine: item)
                        self.enterpriseSecondLevelMedicines.append(enterpriseSecondLevelMedicine)
                        self.isExpand = [Bool](count: self.enterpriseSecondLevelMedicines.count, repeatedValue: false)
                    }
                    if let forthMedicine = value["childTypes"] as? [Dictionary<String, AnyObject>] {
                        for item in forthMedicine {
                        let enterpriseForthLevelMedicine = EnterpriseForthLevelMedicine(enterpriseForthLevelMedicine:item)
                            self.enterpriseForthLevelID = enterpriseForthLevelMedicine.enterpriseForthLevelID
                            self.enterpriseFourthLevelMedicines.append(enterpriseForthLevelMedicine)
                        }
                    }
                }
                NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                    self.medicineTableView.reloadData()
                    MBProgressHUD.hideHUDForView(self.view, animated: true)
                })
            }
            else {
                //错误处理
            }
        }

    }
}